#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

int main(int argc, char **argv)
{
	int sockfd;
	int len;
	struct sockaddr_in addr;
	int result;
	int sel_len;

	int buff_len;
	char buff[1024];
	fd_set read_set;

	assert(argc == 3 && argv[1] && argv[2]);

	FD_ZERO(&read_set);


	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr(argv[1]);
	addr.sin_port = htons(atoi(argv[2]));

	len = sizeof(addr);
	if(0 != (result = connect(sockfd, (struct sockaddr *)&addr, len)))
	{
		perror("connect");
		exit(-1);
	}

	FD_SET(0, &read_set);
	FD_SET(sockfd, &read_set);

	while(1)
	{
		sel_len = select(sockfd + 1, &read_set, NULL, NULL, NULL);
		if (sel_len < 0)
		{
			perror("select");
			continue;
		}

		while(sel_len-- > 0)
		{
			if (FD_ISSET(0, &read_set))
			{
				buff_len = read(0, buff, 1024);
				write(sockfd, buff, buff_len);
			}

			if (FD_ISSET(sockfd, &read_set))
			{
				buff_len = read(sockfd, buff, 1024);
				write(0, buff, buff_len);
			}
		}

		FD_ZERO(&read_set);
		FD_SET(0, &read_set);
		FD_SET(sockfd, &read_set);
	}

	return 0;
}
